package com.novel.task;

import java.sql.Connection;
import java.util.LinkedList;
import java.util.List;

import com.novel.bean.CrawlerBean;
import com.novel.bean.SectionBean;
import com.novel.dao.NovelDao;
import com.novel.service.CrawlerHelper;
import com.novel.utils.Database;


public class CrawlerSectionTask implements Runnable{
	
	private int delay = 50;
	private int terminal = 30;
	private List<SectionBean> sectionList = new LinkedList<>();
	private Long bookid;
	private CrawlerBean crawler;
	boolean stop = false;
	private String bookName;
	
	public CrawlerSectionTask(Long bookid,int delay,List<SectionBean> sectionList,CrawlerBean crawler,String bookName) {
		this.delay = delay;
		this.sectionList = sectionList;
		this.bookid = bookid;
		this.crawler = crawler;
		this.bookName = bookName;
	}
	public void stop(){
		this.stop = true;
	}
	
	public List<SectionBean> getSectionList(){
		return sectionList;
	}
	public int getDelay(){
		return delay;
	}
	public int remainNum(){
		synchronized (sectionList) {
			return sectionList.size();
		}
	}
	public String getBookName(){return bookName;}

	@Override
	public void run() {
		SectionBean sec = null;
		while(!stop){
			synchronized (sectionList) {
				if(sectionList.size() == 0){
					break;
				}
				sec = sectionList.remove(0);
			}
			Connection conn = null;
			try {
				SectionBean section = CrawlerHelper.getSec(sec.getContent(),sec.getNum(), crawler);
				section.setBookid(bookid);
				conn = Database.DB.getConnection();
				NovelDao.novelDAO.insertSection(conn, section);
			} catch (Exception e) {
				System.out.println("读取章节信息发生异常，书籍id："+bookid+",章节链接："+sec.getContent()+"错误信息："+e.toString());
				synchronized (sectionList) {
					sectionList.add(sec);
				}
				try {
					terminal+=10;
					Thread.sleep(terminal*1000);
					delay += 300;
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}finally {
				Database.DB.close(conn);
				try {
					Thread.sleep(delay);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
		System.out.println("================================================");
		System.out.println("===================书籍id:"+bookid+",该书已经爬取完毕===============");
		System.out.println("================================================");
	}
}
